package com.baidunewmusic;

import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import org.apache.http.util.ByteArrayBuffer;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;


import android.os.Parcel;
import android.os.Parcelable;


public class Playlist {
	
	static final public String BAIDU_URL = "http://xinge.baidu.com";
	
	private String coverURL;
	private String lrcURL;
	private String hashedURL;

	private static Playlist uniqueInstance;
	
	private ArrayList<Song> songs = new ArrayList<Song>();
	
	public ArrayList<Song> getSongs(){
		
		return songs;
	}
	
	private Playlist() {
		// TODO Auto-generated constructor stub
	}
	
	
	public static synchronized Playlist getInstance() {
		if (uniqueInstance == null) {
			uniqueInstance = new Playlist();
		}
		return uniqueInstance;
	}
	
	public void load(){
		final String html = getPageSource(BAIDU_URL + "/");
		// 
		parseUrls(html);
		parsePage(html);
	}
	
	private void parseUrls(String page) {
    	final String startPattern = "Xinge.baseurl=";
    	int start = page.indexOf(startPattern) + startPattern.length();
        int end = page.indexOf("}", start);
        String content = page.substring(start, end+1);
        
        
        try {
			JSONObject j = new JSONObject(content);
			coverURL =  j.get("cover").toString();
			lrcURL = j.get("lrc").toString();
			hashedURL = j.get("hashedurl").toString();
			
			
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    }
    
	
	
	public static String getEncoding(String str) {  
        String encode = "GB2312";  
        try {  
            if (str.equals(new String(str.getBytes(encode), encode))) {  
                String s = encode;  
                return s;  
            }  
        } catch (Exception exception) {  
        }  
        encode = "ISO-8859-1";  
        try {  
            if (str.equals(new String(str.getBytes(encode), encode))) {  
                String s1 = encode;  
                return s1;  
            }  
        } catch (Exception exception1) {  
        }  
        encode = "UTF-8";  
        try {  
            if (str.equals(new String(str.getBytes(encode), encode))) {  
                String s2 = encode;  
                return s2;  
            }  
        } catch (Exception exception2) {  
        }  
        encode = "GBK";  
        try {  
            if (str.equals(new String(str.getBytes(encode), encode))) {  
                String s3 = encode;  
                return s3;  
            }  
        } catch (Exception exception3) {  
        }  
        encode = "BIG5";  
        try {  
            if (str.equals(new String(str.getBytes(encode), encode))) {  
                String s4 = encode;  
                return s4;  
            }  
        } catch (Exception exception3) {  
        }  
        return "";  
    }  
	public   static   String   GBToUnicode(String   strIn)   
    {   
        byte[]   b;   
        String   strOut   =   null;   
        if(strIn   ==   null   ||   (strIn.trim()).equals(""))   
            return   strIn;   
        try   
        {   
            b   =   strIn.getBytes("ISO8859_1");   
            strOut   =   new   String(b,"GB2312");   
        }   
        catch(Exception   e)   
        {   
            System.out.println("GBToUnicode   exception   :   "   +   e.getMessage()   +   "\n");   
        }   
        return   strOut;   
    }   
	
    private void parsePage(String page) {
    	final String startPattern = "Data.Nlist.store = ";
    	int start = page.indexOf(startPattern) + startPattern.length();
        int end = page.indexOf("]", start);
        String content = page.substring(start, end+1);
        
        
        try {
			JSONArray j = new JSONArray(content);
			songs.clear();
			for(int i=0; i<j.length();i++){
				Song s = new Song();
				
				s.album = j.getJSONObject(i).get("al").toString();
				s.title =  j.getJSONObject(i).get("ti").toString();
				s.lyrics =  lrcURL + j.getJSONObject(i).get("lrc").toString();
				s.cover =  coverURL + j.getJSONObject(i).get("cv").toString();
				s.url = hashedURL+  j.getJSONObject(i).get("sid").toString();
				s.publishDate =  j.getJSONObject(i).get("da").toString();
				s.artist =  j.getJSONObject(i).get("si").toString();
				s.copy  =  j.getJSONObject(i).get("cp").toString();
				songs.add(0, s);
			}
			songs.trimToSize();
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    }
    
    public static String getPageSource(String url) {
    	try {
			
			String s =  url;
			URL epgURL = new URL(s);
			
			HttpURLConnection conn = (HttpURLConnection) epgURL.openConnection();
			conn.setDoInput(true);
			conn.setConnectTimeout(10000);
			
			conn.setRequestMethod("GET");
			conn.setRequestProperty("accept", "*/*");
			conn.setRequestProperty("User-Agent","Mozilla/4.0"); 
			String location = conn.getRequestProperty("location");
			int resCode = conn.getResponseCode();
			conn.connect();
			InputStream stream = conn.getInputStream();
			byte[] data=new byte[102400];
			int n;
			ByteArrayBuffer buf = new ByteArrayBuffer(102400);
			while ((n = stream.read(data)) != -1 )
				buf.append(data, 0, n);
			String str = new String(buf.toByteArray(),"GB2312");
			conn.disconnect();
			//System.out.println(str);
			stream.close();
			//Log.d(getClass().getSimpleName(), "Link: " + s + " ResCode:" + resCode +" Result:" + str);
			return str;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}
    }
	
	public static class Song  implements Parcelable {

		public String publishDate;
		public String title;
		public String artist;
		public String album;
		public String lyrics;
		public String cover;
		public String url;
		public String copy;
		
		public Song() {
			// TODO Auto-generated constructor stub
		}
		
		public static final Parcelable.Creator<Song> CREATOR = new Creator<Song>() {

			public Song createFromParcel(Parcel source) {
				// TODO Auto-generated method stub
				Song s = new Song();
				s.publishDate = source.readString();
				s.title = source.readString();
				s.artist = source.readString();
				s.album = source.readString();
				s.lyrics = source.readString();
				s.cover = source.readString();
				s.url = source.readString();
				s.copy = source.readString();
				
				return s;
			}

			public Song[] newArray(int size) {
				// TODO Auto-generated method stub
				return new Song[size];
			}
			
		};

		@Override
		public int describeContents() {
			// TODO Auto-generated method stub
			return 0;
		}

		@Override
		public void writeToParcel(Parcel dest, int arg1) {
			dest.writeString(publishDate);
			dest.writeString(title);
			dest.writeString(artist);
			dest.writeString(album);
			dest.writeString(lyrics);
			dest.writeString(cover);
			dest.writeString(url);
			dest.writeString(copy);
			
		}

	}
}
